package com.zy.controller;

import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.serializer.SerializerFeature;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.zy.entity.Apply;
import com.zy.entity.JsonResult;
import com.zy.entity.User;
import com.zy.mapper.DepartmentMapper;
import com.zy.mapper.PostMapper;
import com.zy.mapper.UserMapper;
import com.zy.service.impl.ApplyServiceImpl;
import com.zy.tools.appletsTools.TimeTool;
import org.activiti.engine.*;
import org.activiti.engine.history.HistoricProcessInstance;
import org.activiti.engine.history.HistoricTaskInstance;
import org.activiti.engine.task.Task;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;

import java.text.ParseException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("/app")
public class ApplyController {

    private static final String APPLY_KEY = "applyProcess";//流程key
    @Autowired
    ApplyServiceImpl applyService;
    @Autowired
    DepartmentMapper departmentMapper;
    @Autowired
    PostMapper postMapper;
    @Autowired
    UserMapper userMapper;
    JSONObject jsonObject = new JSONObject();
    @Autowired
    TimeTool timeTool;
    @Autowired
    private TaskService taskService;
    @Autowired
    private RuntimeService runtimeService;
    @Autowired
    private HistoryService historyService;

    /**
     * 创建申请，并开启流程
     *
     * @param apply
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "/createApply")
    public JsonResult createApply(Apply apply) {
        Integer res = applyService.addApply(apply);//创建申请
        Integer applyId = apply.getId();
        Integer departmentId = apply.getDepartmentId();
        QueryWrapper queryWrapper = new QueryWrapper();
        queryWrapper.eq("department_id", departmentId);
        QueryWrapper queryWrapper1 = new QueryWrapper();
        queryWrapper1.eq("post", "总经理");
        Integer leaderId = departmentMapper.selectOne(queryWrapper).getManagerId();//根据部门id查询部门负责人id
        Integer managerId = userMapper.selectOne(queryWrapper1).getId();//根据职位名称查询总经理id
        Map<String, Object> map = new HashMap<>();//设置领导审批
        map.put("self", apply.getUserId());
        map.put("leader", leaderId);
        map.put("manger", managerId);
        runtimeService.startProcessInstanceByKey(APPLY_KEY, String.valueOf(applyId), map);
        this.completeSelf(apply.getUserId().toString());
        if (apply.getUserId() == leaderId) {//如果是部门负责人自己申请
            this.completeSelfLeader(apply.getUserId().toString(), applyId, 0);
        }
        if (res == 1) {
            return new JsonResult("200", "申请创建成功", "1");
        }
        return new JsonResult("201", "申请创建失败", "0");
    }

    /**
     * 完成自己的所有方法
     *
     * @param userId
     */
    public void completeSelf(String userId) {
        List lsit = new ArrayList();
        List<Task> taskList = taskService.createTaskQuery()
                .processDefinitionKey(APPLY_KEY)
                .taskAssignee(userId)
                .list();
        for (int i = 0; i < taskList.size(); i++) {
            taskService.complete(taskList.get(i).getId());
        }
    }

    /**
     * 领导自动完成自己的所有申请
     *
     * @date 2021-04-17 11:11
     */
    public void completeSelfLeader(String userId, Integer applyId, Integer applyState) {
        List lsit = new ArrayList();
        List<Task> taskList = taskService.createTaskQuery()
                .processDefinitionKey(APPLY_KEY)
                .taskAssignee(userId)
                .list();
        for (int i = 0; i < taskList.size(); i++) {
            Map<String, Object> map = new HashMap();
            map.put("msg", "true");
            Apply apply = new Apply();
            apply.setId(applyId);
            apply.setApplyState(applyState + 1);
            taskService.complete(taskList.get(i).getId(), map);
            applyService.updateById(apply);
        }
    }

    /**
     * 查询用户 要操作的流程
     */
    @ResponseBody
    @RequestMapping(value = "/taskQuery")
    public JsonResult taskQuery(String userId) {
        //获取当前用户的所有任务
        List lsit = new ArrayList();
        List<Task> taskList = taskService.createTaskQuery()
                .processDefinitionKey(APPLY_KEY)
                .taskAssignee(userId)
                .list();
        for (int i = 0; i < taskList.size(); i++) {
            //历史流程实例
            HistoricProcessInstance historicProcessInstance = ProcessEngines.getDefaultProcessEngine().getHistoryService().createHistoricProcessInstanceQuery().processInstanceId(taskList.get(i).getProcessInstanceId()).singleResult();
            String applyId = historicProcessInstance.getBusinessKey();
            Apply apply = applyService.getById(applyId);//拿到申请
            User user = userMapper.selectById(apply.getUserId());//拿到用户
            Map map = new HashMap();
            map.put("apply", apply);
            map.put("post", user.getPost());
            map.put("path", user.getPath());
            map.put("name", user.getName());
            map.put("taskId", taskList.get(i).getId());
            lsit.add(map);
        }

        String result = jsonObject.toJSONStringWithDateFormat(lsit, "yyyy-MM-dd", SerializerFeature.WriteDateUseDateFormat);
        return new JsonResult("200", "查询成功", result);
    }

    /**
     * 根据任务id完成任务
     *
     * @param taskId
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "/completeTask")
    public JsonResult completeTask(String taskId, Integer applyId, Integer applyState, String msg) {
        Apply apply = new Apply();
        apply.setId(applyId);

        Map<String, Object> map = new HashMap();
        map.put("msg", msg);
        taskService.complete(taskId, map);
        if (msg.equals("true")) {
            apply.setApplyState(applyState + 1);
        } else {
            apply.setApplyState(-1);
        }
        boolean bool = applyService.updateById(apply);
        if (bool == true) {
            return new JsonResult("200", "成功", apply);
        }
        return new JsonResult("201", "失败", apply);
    }

    /**
     * 查询用户 进行中流程
     *
     * @param uid
     * @return com.zy.entity.JsonResult
     * @author 小宁
     * @date 2021-04-16 16:51
     */
    @ResponseBody
    @RequestMapping(value = "/getApplyList")
    public JsonResult getApplyList(Integer uid) {
        List<Map> applyList = applyService.getApplyList(uid);
        String res = jsonObject.toJSONStringWithDateFormat(applyList, "yyyy-MM-dd", SerializerFeature.WriteDateUseDateFormat);
        return new JsonResult("200", "", res);
    }


    /**
     * 查询用户 成功和驳回记录
     *
     * @param uid
     * @return com.zy.entity.JsonResult
     * @author 小宁
     * @date 2021-04-16 16:51
     */
    @ResponseBody
    @RequestMapping(value = "/getApplyListAnd")
    public JsonResult getApplyListAnd(Integer uid) {
        List<Map> applyList = applyService.getApplyListAnd(uid);
        String res = jsonObject.toJSONStringWithDateFormat(applyList, "yyyy-MM-dd", SerializerFeature.WriteDateUseDateFormat);
        return new JsonResult("200", "", res);
    }

    /**
     * 查询用户已经完成的任务
     */
    @ResponseBody
    @GetMapping(value = "/getHistoryList")
    public JsonResult getHistoryList(String userId) {
        List<Map> lsit = new ArrayList();
        List<HistoricTaskInstance> taskList = historyService.createHistoricTaskInstanceQuery().taskAssignee(userId).finished().list();//获取用户所有已经处理完成的任务
        for (int i = 0; i < taskList.size(); i++) {
            //历史流程实例
            HistoricProcessInstance historicProcessInstance = ProcessEngines.getDefaultProcessEngine().getHistoryService().createHistoricProcessInstanceQuery().processInstanceId(taskList.get(i).getProcessInstanceId()).singleResult();
            String applyId = historicProcessInstance.getBusinessKey();
            Apply apply = applyService.getById(applyId);//拿到申请
            User user = userMapper.selectById(apply.getUserId());//拿到用户
            System.out.println(user);
            if (user.getId() != null && user.getId() != Integer.parseInt(userId)) {
                Map map = new HashMap();
                map.put("apply", apply);
                map.put("post", user.getPost());
                map.put("path", user.getPath());
                map.put("name", user.getName());
                map.put("taskId", taskList.get(i).getId());
                lsit.add(map);
            }
        }
        System.out.println(lsit);
        String result = jsonObject.toJSONStringWithDateFormat(lsit, "yyyy-MM-dd", SerializerFeature.WriteDateUseDateFormat);
        return new JsonResult("200", "", result);
    }

    /**
     * 查询用户在此时间是否请假
     *
     * @param uid
     * @param date
     * @return com.zy.entity.JsonResult
     * @author 小宁
     * @date 2021-04-18 18:50
     */
    @ResponseBody
    @GetMapping("/getLeaveStatus")
    public JsonResult getLeaveStatus(Integer uid, String date) throws ParseException {
        QueryWrapper<Apply> queryWrapper = new QueryWrapper<Apply>();
        queryWrapper.eq("user_id", uid);
        queryWrapper.and(wrapper -> wrapper.eq("apply_state", 1).or().eq("apply_state", 2));

        List<Apply> applyList = applyService.list(queryWrapper);
        for (int i = 0; i < applyList.size(); i++) {

            System.out.println(applyList.get(i).getUserId());
            //请假开始时间
            long applyStartTime = timeTool.dateToStampLongOther(applyList.get(i).getApplyStartTime());
            //请假结束时间
            long applyEndTime = timeTool.dateToStampLongOther(applyList.get(i).getApplyEndTime());
            //传入查询时间
            long dateLong = timeTool.dateToStampLongOther(date);

            if (applyStartTime <= dateLong && dateLong <= applyEndTime) {
                return new JsonResult("201", "请假", uid);
            }
        }
        return new JsonResult("200", "未请假", uid);
    }
}
